<template>
    <div class="container">
        <el-page-header @back="goBack">
            <template #content>
            <span class="text-large font-600 mr-3">ORDER: {{ data ? data.orderId : '' }}</span>
            </template>
        </el-page-header>
        <div style="width: 100%;" id="description">
            <el-descriptions
                class="margin-top"
                title="Order Base Information"
                :column="2"
                size="default"
                border>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">
                            Order id
                        </div>
                    </template>
                    {{ data ? data.orderId : '' }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">
                            Device id
                        </div>
                    </template>
                    {{ data ? data.deviceId : '' }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">
                            Device Name
                        </div>
                    </template>
                    {{ data ? data.deviceName : '' }}
                </el-descriptions-item>            
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">
                            Country code
                        </div>
                    </template>
                    {{ data ? getCountryCode(data) : '' }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">
                            Phone number
                        </div>
                    </template>
                    {{ data ? data.phonenumber : '' }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">
                            Account
                        </div>
                    </template>
                    {{ data ? data.pk : '' }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">
                            Order Type
                        </div>
                    </template>
                    {{ data ? data.recordType : '' }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">
                            Order Status
                        </div>
                    </template>
                    {{ data ? data.orderStatus : '' }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">
                            Requirement Status
                        </div>
                    </template>
                    {{ data ? data.requirementStatus : '' }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">
                            Created Time
                        </div>
                    </template>
                    {{ data ? getCreated(data) : '' }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">
                            Expired Time
                        </div>
                    </template>
                    {{ data ? getExpired(data) : '' }}
                </el-descriptions-item>
            </el-descriptions>
            <el-divider style="margin: 10px 0px;"/>
            <el-descriptions
                class="margin-top"
                :title="(data ? data.recordType : '') + ' required text information'"
                :column="2"
                size="default"
                border>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">
                            First Name
                        </div>
                    </template>
                    {{ getRequirementTextInfo(data)?.firstName ? getRequirementTextInfo(data)?.firstName : '' }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">
                            Last Name
                        </div>
                    </template>
                    {{ getRequirementTextInfo(data)?.lastName ? getRequirementTextInfo(data)?.lastName : '' }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">
                            Passport Number
                        </div>
                    </template>
                    {{ getRequirementTextInfo(data)?.passportNum ? getRequirementTextInfo(data)?.passportNum : '' }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">
                            Address 1
                        </div>
                    </template>
                    {{ getRequirementTextInfo(data)?.address1 ? getRequirementTextInfo(data)?.address1 : '' }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">
                            Address 2
                        </div>
                    </template>
                    {{ getRequirementTextInfo(data)?.address2 ? getRequirementTextInfo(data)?.address2 : '' }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">
                            City
                        </div>
                    </template>
                    {{ getRequirementTextInfo(data)?.city ? getRequirementTextInfo(data)?.city : '' }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">
                            Country
                        </div>
                    </template>
                    {{ getRequirementTextInfo(data)?.country ? (codeToCountryMap.get(getRequirementTextInfo(data)?.country) + ` (${getRequirementTextInfo(data)?.country})`) : '' }}
                </el-descriptions-item>                                                                                               
            </el-descriptions>
            <el-divider style="margin: 10px 0px;"/>
            <el-descriptions
                class="margin-top"
                :title="(data ? data.recordType : '') + ' required files information'"
                :column="2"
                size="default"
                border v-if="data ? data.recordType == 'order' : false">
                <el-descriptions-item>
                    <template #label>
                        <el-button type="primary" @click="onDownload(getRequirementFileInfo(data)?.proofPersonId)" v-if="getRequirementFileInfo(data)?.proofPersonId" style="height: 100%;">
                            <div class="cell-item">
                                Proof of Person ID
                            </div>
                        </el-button>
                        <div v-else class="cell-item">
                            Proof of Person ID
                        </div>
                    </template>
                    <div style="display: flex; flex-direction: row; justify-content: space-between; align-items: center;">
                        <div>{{ getRequirementFileInfo(data)?.proofPersonId ? getRequirementFileInfo(data)?.proofPersonId : '' }}</div>
                        <el-button circle @click="onDelete($event, 'proofPersonId')" v-if="getRequirementFileInfo(data)?.proofPersonId">
                            <img src="../assets/delete.png" style="width: 30px; height: 30px; border-radius: 50%;"/>
                        </el-button>
                    </div>
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <el-button type="primary" @click="onDownload(getRequirementFileInfo(data)?.proofBusinessId)" v-if="getRequirementFileInfo(data)?.proofBusinessId" style="height: 100%;">
                            <div class="cell-item">
                                Proof of Business ID
                            </div>
                        </el-button>
                        <div v-else class="cell-item">
                            Proof of Business ID
                        </div>
                    </template>
                    <div style="display: flex; flex-direction: row; justify-content: space-between; align-items: center;">
                        <div>{{ getRequirementFileInfo(data)?.proofBusinessId ? getRequirementFileInfo(data)?.proofBusinessId : '' }}</div>
                        <el-button circle @click="onDelete($event, 'proofBusinessId')" v-if="getRequirementFileInfo(data)?.proofBusinessId">
                            <img src="../assets/delete.png" style="width: 30px; height: 30px; border-radius: 50%;"/>
                        </el-button>
                    </div>
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <el-button type="primary" @click="onDownload(getRequirementFileInfo(data)?.proofLocalAddr)" v-if="getRequirementFileInfo(data)?.proofLocalAddr" style="height: 100%;">
                            <div class="cell-item">
                                Proof of Local Address
                            </div>
                        </el-button>
                        <div v-else class="cell-item">
                            Proof of Local Address
                        </div>
                    </template>
                    <div style="display: flex; flex-direction: row; justify-content: space-between; align-items: center;">
                        <div>{{ getRequirementFileInfo(data)?.proofLocalAddr ? getRequirementFileInfo(data)?.proofLocalAddr : '' }}</div>
                        <el-button circle @click="onDelete($event, 'proofLocalAddr')" v-if="getRequirementFileInfo(data)?.proofLocalAddr">
                            <img src="../assets/delete.png" style="width: 30px; height: 30px; border-radius: 50%;"/>
                        </el-button>
                    </div>
                </el-descriptions-item>                
            </el-descriptions>
            <el-descriptions
                class="margin-top"
                :title="(data ? data.recordType : '') + ' required files information'"
                :column="2"
                size="default"
                border v-if="data ? data.recordType == 'porting' : false">
                <el-descriptions-item>
                    <template #label>
                        <el-button type="primary" @click="onDownload(getRequirementFileInfo(data)?.proofPersonId)" v-if="getRequirementFileInfo(data)?.proofPersonId" style="height: 100%;">
                            <div class="cell-item">
                                Proof of Person ID
                            </div>
                        </el-button>
                        <div v-else class="cell-item">
                            Proof of Person ID
                        </div>
                    </template>
                    <div style="display: flex; flex-direction: row; justify-content: space-between; align-items: center;">
                        <div>{{ getRequirementFileInfo(data)?.proofPersonId ? getRequirementFileInfo(data)?.proofPersonId : '' }}</div>
                        <el-button circle @click="onDelete($event, 'proofPersonId')" v-if="getRequirementFileInfo(data)?.proofPersonId">
                            <img src="../assets/delete.png" style="width: 30px; height: 30px; border-radius: 50%;"/>
                        </el-button>
                    </div>                        
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <el-button type="primary" @click="onDownload(getRequirementFileInfo(data)?.proofBusinessId)" v-if="getRequirementFileInfo(data)?.proofBusinessId" style="height: 100%;">
                            <div class="cell-item">
                                Proof of Business ID
                            </div>
                        </el-button>
                        <div v-else class="cell-item">
                            Proof of Business ID
                        </div>
                    </template>
                    <div style="display: flex; flex-direction: row; justify-content: space-between; align-items: center;">
                        <div>{{ getRequirementFileInfo(data)?.proofBusinessId ? getRequirementFileInfo(data)?.proofBusinessId : '' }}</div>
                        <el-button circle @click="onDelete($event, 'proofBusinessId')" v-if="getRequirementFileInfo(data)?.proofBusinessId">
                            <img src="../assets/delete.png" style="width: 30px; height: 30px; border-radius: 50%;"/>
                        </el-button>
                    </div>
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <el-button type="primary" @click="onDownload(getRequirementFileInfo(data)?.letterAuth)" v-if="getRequirementFileInfo(data)?.letterAuth" style="height: 100%;">
                            <div class="cell-item">
                                Letter of Authetication
                            </div>
                        </el-button>
                        <div v-else class="cell-item">
                            Letter of Authetication
                        </div>
                    </template>
                    <div style="display: flex; flex-direction: row; justify-content: space-between; align-items: center;">
                        <div>{{ getRequirementFileInfo(data)?.letterAuth ? getRequirementFileInfo(data)?.letterAuth : '' }}</div>
                        <el-button circle @click="onDelete($event, 'letterAuth')" v-if="getRequirementFileInfo(data)?.letterAuth">
                            <img src="../assets/delete.png" style="width: 30px; height: 30px; border-radius: 50%;"/>
                        </el-button>
                    </div>
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <el-button type="primary" @click="onDownload(getRequirementFileInfo(data)?.invoicePortinNum)" v-if="getRequirementFileInfo(data)?.invoicePortinNum" style="height: 100%;">
                            <div class="cell-item">
                                Invoice of Porting Number
                            </div>
                        </el-button>
                        <div v-else class="cell-item">
                            Invoice of Porting Number
                        </div>
                    </template>
                    <div style="display: flex; flex-direction: row; justify-content: space-between; align-items: center;">
                        <div>{{ getRequirementFileInfo(data)?.invoicePortinNum ? getRequirementFileInfo(data)?.invoicePortinNum : '' }}</div>
                        <el-button circle @click="onDelete($event, 'invoicePortinNum')" v-if="getRequirementFileInfo(data)?.invoicePortinNum">
                            <img src="../assets/delete.png" style="width: 30px; height: 30px; border-radius: 50%;"/>
                        </el-button>
                    </div>
                </el-descriptions-item>
            </el-descriptions>

            <div style="margin-top: 20px; display: flex; flex-direction: row; justify-content: flex-end; align-items: center; gap: 20px;">
                <el-button type="success" size="large" @click="onPhoneNumberStatus">Phonenumber Status</el-button>
                <el-button type="success" size="large" @click="onRequirementStatus">Requirement Status</el-button>
            </div>
        </div>
    </div>
    <el-dialog
        id="dlg"
        v-model="dialog"
        :title="title"
        width="500"
        destroy-on-close
        center
        >
        <div style="width: 100%; padding: 20px; box-sizing: border-box; height: 300px; display: flex; flex-direction: column; justify-content: space-evenly; align-items: center;">
            <div>{{ dialogText }}</div>
            <el-select
                v-model="status"
                placeholder="Select"
                size="large"
                style="width: 100%"
                >
                <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
            </el-select>
        </div>
        <template #footer>
            <div style="display: flex; flex-direction: row; justify-content: center; align-items: center; gap: 20px;">
                <el-button type="primary" @click="onConfirm">Confirm</el-button>
                <el-button @click="dialog = false">Cancel</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { onMounted, ref} from 'vue';
import { useGlobalStore } from '../store';
import { useRoute, useRouter } from 'vue-router';
import { api_get_deviceItem, api_update_device, api_update_deviceItem, codeToCountryMap, getFileUrl } from '../api/apis';
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus';
    const store = useGlobalStore();
    const route = useRoute();
    const router = useRouter();
    const data: any = ref(null);
    const dialog = ref(false);
    const title = ref('')
    const options = ref<any[]>([])
    const status = ref('')
    const dialogText = ref('')
    let statusType = ''

    const onPhoneNumberStatus = () => {
        statusType = 'number'
        title.value = "Phonenumber Status";
        dialogText.value = "Please select the status you want to change for phonumber status";
        options.value = [
            {
                value: 'pending',
                label: 'pending'
            },
            {
                value: 'valid',
                label: 'valid'
            },
            {
                value: 'expired',
                label: 'expired'
            }
        ]

        dialog.value = true;
    }

    const onRequirementStatus = () => {
        statusType = 'requirement'
        title.value = "Requirement Status";
        dialogText.value = "Please select the status you want to change for requirement status";
        options.value = [
            {
                value: 'pending',
                label: 'pending'
            },
            {
                value: 'submitted',
                label: 'submitted'
            },
            {
                value: 'rejected',
                label: 'rejected'
            },
            {
                value: 'approved',
                label: 'approved'
            }
        ]
        dialog.value = true;
    }

    const onConfirm = async () => {
        let loading = ElLoading.service({
                        target: '#dlg',
                        text: "Logining...",
                    });

        console.log('onConfirm', data.value);
        try {
            const confirmData = {} as any;
            confirmData.deviceId = data.value.deviceId;
            if (statusType == 'number') {
                confirmData.orderStatus = status.value;
            }else {
                confirmData.requirementStatus = status.value;
            }
            const ret = await api_update_deviceItem(data.value.pk, confirmData);
            console.log('api_update_deviceItem', ret);
            if (ret.status == 200) {
                if (ret.data.errCode == 0) {
                    ElMessage.success('Success');
                    return;
                }
            }

            ElMessage.error('Failed');
        }catch (err: any) {
            console.log(err);
            ElMessage.error('Failed');
        }finally {
            loading.close();
            dialog.value = false;
        }
    }
    
    onMounted(() => {
        const params = route.params;
        console.log('query', params);
        const id = params.id as string;
        const index = store.orderList.findIndex((item: any) => item.orderId == id);
        console.log('findIndex index', index);
        
        if (index != -1) {
            (async () => {
                let loading = ElLoading.service({
                        target: '#description',
                        text: "Logining...",
                    });

                try {
                    const ret = await api_get_deviceItem(store.orderList[index].account, store.orderList[index].deviceId);
                    console.log('api_get_deviceItem', ret);
                    if (ret.status == 200) {
                        data.value = ret.data.data;
                    }
                }catch (err: any) {
                    console.log(err);
                    router.back();                    
                }finally {
                    loading.close();
                }
            })();
        }else {
            data.value = null;
            router.back();
        }
    })

    const getCountryCode = (data: any) => {
        let countryCode;
        console.log('data', data);
        console.log('data.recordType', data.recordType);
        

        if (data.recordType == 'order') {
            for (let i = 0; i < data.orderInfo.regionType.length; i++) {
                if (data.orderInfo.regionType[i].regionType == 'country_code') {
                    countryCode = data.orderInfo.regionType[i].regionName;
                    break;
                }
            }
        }else {
            countryCode = data.reportingInfo.countryCode;
        }

        console.log('countryCode', countryCode);
        

        return codeToCountryMap.get(countryCode) + ` (${countryCode})`;
    }

    const getCreated = (data: any) => {
        let createdTime;
        if (data.recordType == 'order') {
            createdTime = data.orderInfo.created;
        }else {
            createdTime = data.reportingInfo.created;
        }

        return new Date(createdTime * 1000).toLocaleString();
    }

    const getExpired = (data: any) => {
        let expiredTime;
        if (data.recordType == 'order') {
            expiredTime = data.orderInfo.expired;
        }else {
            expiredTime = data.reportingInfo.expired;
        }

        return new Date(expiredTime * 1000).toLocaleString();
    }

    const getRequirementTextInfo = (data: any) => {
        if (data == null) {
            return null;  
        }

        return data.requirementTextInfos
    }

    const getRequirementFileInfo = (data: any) => {
        if (data == null) {
            return null;  
        }

        return data.requirementFileInfos
    }

    const goBack = () => {
        router.go(-1);
    }

    const onDownload = async (filename: string) => {
        let loading = ElLoading.service({
            fullscreen: true,
            text: "Logining..."
        })
        try {
            const ret = await getFileUrl(filename);
            console.log('getFileUrl', ret);
            if (ret != '') {
                // window download url
                window.open(ret);
            }
        }catch (err: any) {
            ElMessage.error('Download Failed');
        }finally {
            loading.close();
        }
    }

    const onDelete = async (e: any, index: string) => {

        console.log("onDelete", data.value, e);
        

        ElMessageBox.confirm(
            `Clear ${index} attribute of file requirement, are you sure?`,
            'Warning',
            {
                confirmButtonText: 'OK',
                cancelButtonText: 'Cancel',
                type: 'warning',
        })
        .then(async () => {
            let loading = ElLoading.service({
            fullscreen: true,
            text: "Logining..."})
            try {
                let deleteData = {} as any;
                deleteData['requirementFileInfos'] = data.value['requirementFileInfos'];
                deleteData['requirementFileInfos'][index] = ""
                deleteData['deviceId'] = data.value.deviceId
                deleteData['requirementStatus'] = 'pending'

                const ret = await api_update_device(data.value.pk, deleteData)
                console.log('api_update_device', ret);
                if (ret.status == 200) {
                    if (ret.data.errCode == 0) {
                        data.value.requirementFileInfos[index] = '';
                        ElMessage.success('Success');
                        return;
                    }
                }

                ElMessage.error('Delete Failed');
            }catch (err: any) {
                console.log(err);
                ElMessage.error('Delete Failed');
            }finally {
                loading.close();
            }
        })
    }
</script>

<style scoped>
.container {
    width: 100%;
    height: 100%;
    overflow: scroll;
    padding: 20px;
    box-sizing: border-box;
}

.cell-item {
  display: flex;
  align-items: center;
}

.margin-top {
  margin-top: 20px;
}
</style>